<template>
	<view class="main">
		<u-navbar :is-back="true" title="连接打印机" :background="background" back-icon-color="#000000" title-color="#000"
			title-bold="true"></u-navbar>
		<view class="whole">
			<view class="top">
				<text>连接设备</text>
				<image :class="plus==true?'zhuan':'bzhuan'" src="../../../static/images/sx.png" mode=""
					:loading="isSearching" @click="xuan">
				</image>
			</view>
			<block>
				<view class="all" @click="changes(item,index)" v-for="(item,index) in list" :data-title="item.deviceId"
					:data-name="item.name" :data-advertisData="item.advertisServiceUUIDs" :key="item.deviceId">
					<view :class="status==2&&indes==index?'ly':'ly2'">
						<view class="left">
							<image
								:src="status==2&&indes==index?'../../../static/images/ly.png':'../../../static/images/lyed.png'"
								mode=""></image>
							<view class="l_txt">
								<view>{{item.name}}</view>
								<text class="status" v-if="indes==index&&show!=false">正在连接....</text>
								<text class="status" v-if="status==2&&indes==index">已连接</text>
							</view>
						</view>
						<view class="right">
							<image
								:src="status==2&&indes==index?'../../../static/images/righted.png':'../../../static/images/righte.png'"
								mode=""></image>
						</view>
					</view>
				</view>
			</block>
		</view>
		<u-popup v-model="show" mode="bottom" border-radius="34">
			<view class="bottom">
				<view class="ly_tit">{{printer.name}}连接吗？</view>
				<view class="button">
					<view class="qx" @click="qx">
						取消
					</view>
					<view class="qd" @click="bindViewTap">
						配对
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				background: {
					backgroundColor: '#fff'
				},
				show: false,
				status: 0,
				plus: false,
				content: true,
				indes:'',
				printer:'',
				//蓝牙
				isSearching: false, //是否正在搜索中
				list: [],
				services: [],
				serviceId: 0,
				writeCharacter: false,
				readCharacter: false,
				notifyCharacter: false,
			}
		},
		computed: mapState(['sysinfo', 'Bluetooth']),
		onUnload() {
			//停止搜索蓝牙设备
			if (this.isSearching) {
				uni.stopBluetoothDevicesDiscovery();
			}
		},
		onLoad() {
			this.startSearch()
			setTimeout(function() {
				uni.stopBluetoothDevicesDiscovery();
			}, 20000)

		},
		mounted() {

		},
		onShow() {
			this.status=''
		},
		methods: {
			//错误码提示
			errorCodeTip(code) {
				if (code == 0) {
					//正常
				} else if (code == 10000) {
					uni.showToast({
						title: '未初始化蓝牙适配器',
						icon: 'none'
					})
				} else if (code == 10001) {
					uni.showToast({
						title: '当前蓝牙适配器不可用',
						icon: 'none'
					})
				} else if (code == 10002) {
					uni.showToast({
						title: '没有找到指定设备',
						icon: 'none'
					})
				} else if (code == 10003) {
					uni.showToast({
						title: '连接失败',
						icon: 'none'
					})
				} else if (code == 10004) {
					uni.showToast({
						title: '没有找到指定服务',
						icon: 'none'
					})
				} else if (code == 10005) {
					uni.showToast({
						title: '没有找到指定特征值',
						icon: 'none'
					})
				} else if (code == 10006) {
					uni.showToast({
						title: '当前连接已断开',
						icon: 'none'
					})
				} else if (code == 10007) {
					uni.showToast({
						title: '当前特征值不支持此操作',
						icon: 'none'
					})
				} else if (code == 10008) {
					uni.showToast({
						title: '其余所有系统上报的异常',
						icon: 'none'
					})
				} else if (code == 10009) {
					uni.showToast({
						title: 'Android 系统特有，系统版本低于 4.3 不支持 BLE',
						icon: 'none'
					})
				}
			},
			//开始搜索蓝牙
			startSearch() {
				let that = this
				uni.openBluetoothAdapter({
					success(res) {
						uni.getBluetoothAdapterState({
							success(res2) {
								console.log('啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊getBluetoothAdapterState:', res2)
								if (res2.available) {
									that.isSearching = true;
									if (res2.discovering) {
										uni.showToast({
											title: '正在搜索附近打印机设备',
											icon: "none"
										})
										return;
									}
									//获取蓝牙设备信息
									that.getBluetoothDevices()
									// that.checkPemission()
								} else {
									uni.showModal({
										title: '提示',
										content: '本机蓝牙不可用',
									})
								}
							}
						});
					},
					fail() {
						uni.showModal({
							title: '提示',
							content: '蓝牙初始化失败，请打开蓝牙',
						})
					}
				})
			},
			stopSearch() {
				uni.stopBluetoothDevicesDiscovery({
					success: (res) => {
						this.isSearching = false;
						console.log('stop:', res)
					},
					fail: (e) => {
						console.log('stop:', e)
						this.errorCodeTip(e.errCode);
					}
				})
			},
			//校验权限
			checkPemission() {
				let that = this
				let {
					BLEInformation
				} = that.Bluetooth;
				let platform = BLEInformation.platform;
				that.getBluetoothDevices();
				console.log(222);
			},
			//获取蓝牙设备信息
			getBluetoothDevices() {
				let that = this
				that.list = [];
				uni.startBluetoothDevicesDiscovery({
					success(res) {
						console.log(res)
						//蓝牙设备监听 uni.onBluetoothDeviceFound
						uni.onBluetoothDeviceFound((result) => {
							console.log('onBluetoothDeviceFound:', result)
							let arr = that.list;
							let devices = [];
							let list = result.devices;
							for (let i = 0; i < list.length; ++i) {
								if (list[i].name && list[i].name != "未知设备") {
									let arrNew = arr.filter((item) => {
										return item.deviceId == list[i].deviceId;
									});
									// console.log('arrNew:',arrNew.length)
									if (arrNew.length == 0) {
										devices.push(list[i]);
									}
								}
							}

							that.list = arr.concat(devices);
						});
						that.time = setTimeout(() => {
							// uni.getBluetoothDevices
							uni.getBluetoothDevices({
								success(res2) {
									let devices = [];
									let list = res2.devices;
									var that = this



									for (let i = 0; i < list.length; ++i) {
										if (list[i].name && list[i].name != "未知设备") {
											devices.push(list[i]);
										}
									}

									that.list = devices;

									console.log('getBluetoothDevices:', res2);
								},
							})

							clearTimeout(that.time);
						}, 3000);
					}
				});

			},
			//绑定蓝牙
			bindViewTap(e) {
				let that = this;
				// let {
				// 	title
				// } = this.printer.deviceId;
				let {
					BLEInformation
				} = that.Bluetooth;
				this.stopSearch();

				that.serviceId = 0;
				that.writeCharacter = false;
				that.readCharacter = false;
				that.notifyCharacter = false;
				uni.showLoading({
					title: '正在连接',
				})
				console.log('deviceId:', that.printer.deviceId)
				// uni.createBLEConnection
				uni.createBLEConnection({
					deviceId: that.printer.deviceId,
					success(res) {
						console.log('createBLEConnection success:', res)
						BLEInformation.deviceId = that.printer.deviceId;
						that.$store.commit('BLEInformationSet', BLEInformation);
						uni.hideLoading()
						that.getSeviceId()
						
					},
					fail(e) {
						that.errorCodeTip(e.errCode);
						uni.hideLoading()
					}
				})
			},
			//获取蓝牙设备所有服务(service)。
			getSeviceId() {
				let that = this;
				// let {
				// 	BLEInformation
				// } = that.Bluetooth;
				console.log('BLEInformation.deviceId:', that.printer.deviceId)
				// uni.getBLEDeviceServices
				let t = setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: that.printer.deviceId,
						success(res) {
							console.log('getBLEDeviceServices success:', res)
							that.services = res.services;
							that.getCharacteristics()
						},
						fail: function(e) {
							that.errorCodeTip(e.code);
							console.log('getBLEDeviceServices fail:', e)
						}
					})
					clearTimeout(t);
				}, 1500)
				
			},
			getCharacteristics() {
				var that = this
				let {
					services: list,
					serviceId: num,
					writeCharacter: write,
					readCharacter: read,
					notifyCharacter: notify
				} = that;
				let {
					BLEInformation
				} = that.Bluetooth;
				// uni.getBLEDeviceCharacteristics
				uni.getBLEDeviceCharacteristics({
					deviceId: that.printer.deviceId,
					serviceId: list[num].uuid,
					success(res) {
						// console.log(res)
						for (var i = 0; i < res.characteristics.length; ++i) {
							var properties = res.characteristics[i].properties
							var item = res.characteristics[i].uuid
							if (!notify) {
								if (properties.notify) {
									BLEInformation.notifyCharaterId = item;
									BLEInformation.notifyServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									notify = true
								}
							}
							if (!write) {
								if (properties.write) {
									BLEInformation.writeCharaterId = item;
									BLEInformation.writeServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									write = true
								}
							}
							if (!read) {
								if (properties.read) {
									BLEInformation.readCharaterId = item;
									BLEInformation.readServiceId = list[num].uuid;
									that.$store.commit('BLEInformationSet', BLEInformation);
									read = true
								}
							}
						}
						if (!write || !notify || !read) {
							num++
							that.writeCharacter = write;
							that.readCharacter = read;
							that.notifyCharacter = notify;
							that.serviceId = num;
							if (num == list.length) {
								uni.showModal({
									title: '提示',
									content: '找不到该读写的特征值',
								})
							} else {
								that.getCharacteristics()
							}
						} else {
							that.openControl()
						}
					},
					fail: function(e) {
						console.log("getBLEDeviceCharacteristics fail：", e);
						that.errorCodeTip(e.errCode);
					}
				})
			},
			openControl: function() {
				this.status = 2
				this.show = false
				// #ifdef APP-NVUE
				const eventChannel = this.$scope.eventChannel; // 兼容APP-NVUE
				// #endif
				// #ifndef APP-NVUE
				const eventChannel = this.getOpenerEventChannel();
				// #endif
				eventChannel.emit('selectType', this.status);
				uni.navigateBack({
					delta: 1,
				})
			},

			//操作以上为蓝牙搜索

			changes(item,index) {
				console.log(item);
				this.printer=item
			console.log(index);
				this.indes=index
				if (this.status != 2) {
					this.status = 1
					this.show = true
				}
			},
			qd() {
				this.status = 2
				this.show = false
			},
			qx() {
				this.status = 0
				this.show = false
			},
			xuan() {
				let that = this
				that.plus = true
				// that.content=false   ////内容隐藏
				setTimeout(function() {
					that.plus = false
					// that.content=true
				}, 2000)
			}

		}
	}
</script>
<style lang="scss">
	page {
		font-family: PingFang SC;
		width: 750rpx;
		margin: 0 auto;
		background-color: #fff;

		.main {
			width: 750rpx;
			margin: 0 auto;

			.whole {
				.top {
					margin: 27rpx 20rpx 49rpx 35rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;

					text {
						font-size: 30rpx;
						font-weight: 400;
						color: #000000;
					}

					.bzhuan {
						width: 44rpx;
						height: 32rpx;
					}

					.zhuan {
						width: 44rpx;
						height: 32rpx;
						animation: rot 1s linear infinite;
						animation-iteration-count: infinite;
					}

				}

				.all {
					.back {
						background: #F2F2F2 !important;
					}

					.ly {
						display: flex;
						justify-content: space-between;
						align-items: center;
						width: 690rpx;
						margin: 10rpx auto;
						background: #0F82FF;
						border-radius: 40rpx;
						padding: 0 35rpx;

						.left {
							display: flex;
							align-items: center;

							image {
								margin: 54rpx 0;
								width: 34rpx;
								height: 36rpx;
							}

							.l_txt2 {
								view {
									color: #000 !important;
								}

								text {
									color: #4D4D4D !important;
								}
							}

							.l_txt {
								padding-left: 52rpx;

								view {
									font-size: 32rpx;
									font-weight: bold;
									color: #FFFFFF;
								}

								.status {
									font-size: 24rpx;
									font-weight: 400;
									color: #FFFFFF;
								}
							}
						}

						.right {
							image {
								width: 46rpx;
								height: 46rpx;
							}
						}
					}




					.ly2 {
						display: flex;
						justify-content: space-between;
						align-items: center;
						width: 690rpx;
						margin: 10rpx auto;
						background: #F2F2F2;
						border-radius: 40rpx;
						padding: 0 35rpx;

						.left {
							display: flex;
							align-items: center;

							image {
								margin: 54rpx 0;
								width: 34rpx;
								height: 36rpx;
							}

							.l_txt {
								padding-left: 52rpx;

								view {
									font-size: 32rpx;
									font-weight: bold;
									color: #000;
								}

								.status {
									font-size: 24rpx;
									font-weight: 400;
									color: #000;
								}
							}
						}

						.right {
							image {
								width: 46rpx;
								height: 46rpx;
							}
						}
					}








				}
			}

			.bottom {

				width: 750rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 20rpx;

				.ly_tit {
					font-size: 42rpx;
					font-family: PingFang SC;
					font-weight: bold;
					color: #010101;
					padding: 47rpx 0 57rpx 0;
				}

				.button {
					text-align: center;

					.qx {
						margin-bottom: 20rpx;
						background: #F0F0F0;
						padding: 33rpx 0;

						border-radius: 49rpx;
						width: 660rpx;
						font-size: 32rpx;
						font-weight: bold;
						color: #4C4C4C;
					}

					.qd {
						margin-bottom: 20rpx;
						padding: 33rpx 0;
						width: 660rpx;

						font-size: 32rpx;
						font-weight: bold;
						color: #FFFFFF;
						border-radius: 49rpx;
						background: #0D85FF;
					}
				}
			}

			@keyframes rot {

				0% {
					-webkit-transform: rotate(0deg);
				}

				25% {
					-webkit-transform: rotate(90deg);
				}

				50% {
					-webkit-transform: rotate(180deg);
				}

				75% {
					-webkit-transform: rotate(270deg);
				}

				100% {
					-webkit-transform: rotate(360deg);
				}

			}
		}
	}
</style>
